# -*- coding: utf-8 -*-

import os
import yaml
import logging
import logging.config
from typing import Dict

from contract_market import settings
from contract_market.base.type import Self


class InitLogConfig:

    FILNENAME = "filename"
    LOG = "log"

    def __new__(cls, *args, **kwargs) -> Self:

        if not hasattr(cls, "_instance"):
            setattr(cls, "_instance", super().__new__(cls))
        return getattr(cls, "_instance")

    def __init__(self, dirname: str = "", file: str = "log.yaml") -> None:
        """ """
        log_conf = os.path.join(settings.CONFIG_DIR, dirname, file)
        log_path = os.path.join(settings.BASE_DIR, self.LOG)

        with open(log_conf, 'rt') as f:
            config = yaml.safe_load(f.read())
            self.change_filename(log_path, config)

    def change_filename(self, log_path: str, config: dict):
        """ """
        for _k, _v in config["handlers"].items():
            if self.FILNENAME not in _v or not isinstance(_v, Dict):
                continue
            _v[self.FILNENAME] = os.path.join(log_path, _v[self.FILNENAME])
        logging.config.dictConfig(config)
